package com.zhang.admin.service;

import org.neo4j.driver.reactive.ReactiveTransaction;
import org.slf4j.event.DefaultLoggingEvent;

import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @title: 用户角色服务
 * @author: zhang
 * @date: 2023/3/23 下午4:01
 **/
public class UserRoleService {


    /**
     * 根据用户id获取角色id
     * @param userId
     * @return
     */
    public static Long getRoleIdByUserId(long userId){
        try{
            Class.forName(DATABASE.DRIVER);
            var connection = DriverManager.getConnection(
                    DATABASE.URL,
                    DATABASE.USERNAME,
                    DATABASE.PASSWORD
            );

            var selectStatement = connection.prepareStatement(
                    "select role_id from user_role where user_id = ?"
            );
            selectStatement.setLong(1,userId);
            var resultSet = selectStatement.executeQuery();
            Long roleId = null;

            if(resultSet.next()){
                roleId = resultSet.getLong("role_id");
            }
            selectStatement.close();
            connection.close();
            return roleId;
        }catch (SQLException | ClassNotFoundException e){
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 添加用户和角色的关系
     * @param userId
     * @param roleId
     */
    public static void addUserIdRoleIdRelationship(long userId,long roleId){
        try {
            Class.forName(DATABASE.DRIVER);
            var connection = DriverManager.getConnection(
                    DATABASE.URL,
                    DATABASE.USERNAME,
                    DATABASE.PASSWORD
            );
            // 先把用户-角色表中的数据删除
            // 因为默认一个用户只用一个角色
            var deleteStatement = connection.prepareStatement(
                    "delete from user_role where user_id = ?"
            );
            deleteStatement.setLong(1,userId);
            deleteStatement.execute();

            // 插入userId 和 roleId 的关系
            var insertStatement = connection.prepareStatement(
                    "insert into user_role (user_id,role_id) values (?,?)"
            );
            insertStatement.setLong(1,userId);
            insertStatement.setLong(2,roleId);
            insertStatement.execute();

            deleteStatement.close();
            insertStatement.close();
            connection.close();
        }catch (SQLException | ClassNotFoundException e){
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        System.out.println(UserRoleService.getRoleIdByUserId(1));
    }

}
